#include <stdlib.h>
#include <memory.h>

#include "list.h"
/*
 *
 */
list *list_new()
{
    list *lst = malloc(sizeof(list));
    if (lst != NULL) {
        memset(lst, 0, sizeof(list));
    }
    return lst;
}


/*
 *
 */
void list_free(list *lst, list_free_fn nfree)
{
    list_node *curr;
    list_node *next;

    curr = lst->head;
    while (curr != NULL) {
        next = curr->next;
        nfree((void*) curr);
        curr = next;
    }        
    free(lst);
}


/*
 *
 */
int list_delink(list *lst, void *t)
{
    list_node *n = (list_node*) t;

    if (lst == NULL) return (LIST_ENULL);
    
    if (n->prev != NULL) {
        n->prev->next = n->next;
    } else {
        lst->head = n->next;
    }

    if (n->next != NULL) {
        n->next->prev = n->prev;
    } else {
        lst->tail = n->prev;
    }

    n->next = n->prev = NULL;
    lst->count--;
    return (LIST_EOK);    
}


/*
 *
 */
int list_append(list *lst, void *t) 
{
    list_node *end;
    list_node *n = (list_node*) t;
    
    if (lst == NULL) return (LIST_ENULL);
    end = lst->tail;
    if (end != NULL) {
        end->next = n;
        lst->tail = n;
        n->prev = end;
        n->next = NULL;
    } else {
        lst->head = n;
        lst->tail = n;
        n->prev = NULL;
        n->next = NULL;
    }

    lst->count++;
    return (LIST_EOK);
}    


/*
 *
 */
int list_prepend(list *lst, void *t)
{
    list_node *beg;
    list_node *n = (list_node*) t;

    if (lst == NULL) return (LIST_ENULL);
    beg = lst->head;
    if (beg != NULL) {
        beg->prev = n;
        lst->head = n;
        n->prev = NULL;
        n->next = beg;
    } else {
        lst->head = n;
        lst->tail = n;
        n->prev = NULL;
        n->next = NULL;
    }    
    lst->count++;
    return (LIST_EOK);
}


/*
 *
 */
void list_random_insert(list *lst, void *n) 
{
    
}


/*
 *
 */
void list_sort(list *lst, list_compare_fn comp)
{


}

void list_sorted_insert(list *lst, list_compare_fn comp)
{


}

